package com.wuming.caiwu.service.impl;


import com.wuming.caiwu.core.BusinessException;
import com.wuming.caiwu.core.MemberStatus;
import com.wuming.caiwu.core.WumingErrorCode;
import com.wuming.caiwu.core.WumingRole;
import com.wuming.caiwu.dao.MemberMapper;
import com.wuming.caiwu.model.Member;
import com.wuming.caiwu.model.SysRole;
import com.wuming.caiwu.service.MemberService;
import com.wuming.caiwu.service.SysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/***
 * Created by hanfei on 16/5/7.
 */
@Service("memberService")
public class MemberServiceImpl extends BaseServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public void saveMember(Member member) throws BusinessException {
        memberMapper.insertSelective(member);
    }

    @Override
    public void modifyMember(Member member) throws BusinessException {
        memberMapper.updateByPrimaryKeySelective(member);
    }

    @Override
    public void modifyBlanceById(Integer id, BigDecimal blance) throws BusinessException {
        Map<String,Object> params = new HashMap<>();
        if(null != id){
            params.put("id",id);
        }
        if(null != blance){
            params.put("blance",blance);
        }
        memberMapper.updateById(params);
    }

    @Override
    public Member getMemberById(Integer id) throws BusinessException {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void removeMemberById(Integer id) throws BusinessException {
        memberMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void verifyMemberById(Integer id) throws BusinessException {
        Member member = new Member();
        member.setId(id);
        member.setStatus(MemberStatus.STATUS_NORMAL.ordinal());
        memberMapper.updateByPrimaryKeySelective(member);
    }

    @Override
    public Member getMemberByNameAndPassword(String userName, String password) {
        if (StringUtils.isBlank(userName)) {
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
//        if (StringUtils.isBlank(password)) {
//            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_PASSWORD_NULL);
//        }
        Member member = new Member();
        member.setUserName(userName);
        if (StringUtils.isNotBlank(password)) {
            member.setPassword(password);
        }
        return memberMapper.selectByNameAndPassword(member);
    }

    @Override
    public boolean isAdministrator(Member user) {
        SysRole role = sysRoleService.getSysRoleById(user.getRole().longValue());
        if (role.getName().equalsIgnoreCase("平台") || role.getName().equalsIgnoreCase("超级管理员")) {
            return true;
        }
        return false;
    }

    @Override
    public List<Member> getMembersByPage(int pageIndex, int pageSize, Integer memberId, String userName, String company, String phone, Integer status, Integer parentId) throws BusinessException {
        try {
            Map<Object, Object> maps = new HashMap<Object, Object>();
            if (null != parentId) {
                maps.put("parentId", parentId);
            }
            maps.put("userName", userName);
            maps.put("company", company);
            maps.put("phone", phone);
            maps.put("status", status);
            return (List<Member>) this.getPageList(MemberMapper.class, "selectMembers", maps, pageIndex, pageSize);
        } catch (Exception e) {
            logger.error("查询用户信息失败{}" + e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public int getTotal(Integer memberId, String userName, String company, String phone, Integer status, Integer parentId) throws BusinessException {
        try {
            Map<Object, Object> maps = new HashMap<Object, Object>();
            if (null != parentId) {
                maps.put("parentId", parentId);
            }
            maps.put("userName", userName);
            maps.put("company", company);
            maps.put("phone", phone);
            maps.put("status", status);
            return this.getTotal(MemberMapper.class, "selectTotal", maps);
        } catch (Exception e) {
            logger.error("查询用户信息总数失败.异常:{}", e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }


    @Override
    public Member getMemberByPhone(String phone) throws BusinessException {
        Member member = new Member();
        member.setPhone(phone);
        try {
            List<Member> members = memberMapper.selectMembers(member);
            if (null != member && !members.isEmpty()) {
                return members.get(0);
            }
            return null;
        } catch (Exception e) {
            logger.error("根据手机号查询会员失败.异常：{}", e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public Member getMemberByOpenId(String openId) throws BusinessException {
        Member member = new Member();
        member.setOpenid(openId);
        try {
            List<Member> members = memberMapper.selectMembers(member);
            if (null != member && !members.isEmpty()) {
                return members.get(0);
            }
            return null;
        } catch (Exception e) {
            logger.error("根据openId查询会员失败.异常：{}", e.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public List<Member> getChildrens(Integer memberId) {
        return memberMapper.getMemberByParent(memberId);
    }

    @Override
    public List<Member> getPandaMember() throws BusinessException {
        Member member = new Member();
        return memberMapper.selectMembers(member);
    }

    @Override
    public List<Member> getAllMembers() throws BusinessException {
        Member member = new Member();
        member.setStatus(MemberStatus.STATUS_NORMAL.ordinal());

        try {
            List<Member> members = this.memberMapper.selectMembers(member);
            return members;
        } catch (Exception var3) {
            this.logger.error("查询会员异常:{}", var3.getMessage());
            throw new BusinessException(WumingErrorCode.HUIQIAN_USERCENTER_DATABASE_OPERATE_ERROR);
        }
    }

    @Override
    public void getChildMemberIdsByParentId(Integer parentId,List<Integer> memberIds) throws BusinessException {
        //添加当前memberid
        memberIds.add(parentId);
        //查询所有子memberids
        Member params = new Member();
        if(null != parentId){
            params.setParentId(parentId);
        }
        List<Member> members = memberMapper.selectMembers(params);
        if(null != members && !members.isEmpty()){
            for (Member member:members
                 ) {
                Integer currentId = member.getId();
                getChildMemberIdsByParentId(currentId,memberIds);
            }
        }
    }
}
